package com.wzw.springboot.principle.use.security.infrastructure.provider;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Collection;

/**
 * 二维码
 *
 * @author Wangzhiwen
 */
public class QrCodeAuthenticationToken extends AbstractAuthenticationToken {

    private static final long serialVersionUID = -1L;

    private final Object principal;

    private Object credentials;

    /**
     * 未认证
     *
     * @param principal   二维码UUID
     * @param credentials 验证码
     */
    public QrCodeAuthenticationToken(Object principal, Object credentials) {
        super(null);
        this.principal = principal;
        this.credentials = credentials;
        setAuthenticated(false);
    }

    /**
     * 已认证
     *
     * @param principal   二维码UUID
     * @param credentials 验证码
     * @param authorities 权限列表
     */
    public QrCodeAuthenticationToken(Object principal, Object credentials,
                                     Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.credentials = credentials;
        super.setAuthenticated(true); // must use super, as we override
    }

    @Override
    public Object getCredentials() {
        return credentials;
    }

    @Override
    public Object getPrincipal() {
        return principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.credentials = null;
    }
}
